﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GiMessServer.Net;
using GiMessCommons;

namespace GiMessServer
{
    public class GiMessServer
    {
        private NetServer        netServer;
        private NetMsgHandler    msgHandler;

        private DataFieldsReader dataReader;
        private DataFieldsWriter dataWriter;

        public static GiMessServer Instance      { get; private set; }
        //public      NetServer    NetServerInst { get; private set; }

        public GiMessServer()
        {
            Instance = this;
        }

        public void Start()
        {
            netServer  = new NetServer();
            msgHandler = new NetMsgHandler();

            netServer.NewNetMsg += msgHandler.HandleMsg;
             
            Work();
        }

        //Nefolositoare????
        public void Work()
        {
            while (true)
            {
                System.Threading.Thread.Sleep(5);
            }
        }

        #region Complex Server messages

        public void UserIM(string data)
        {
            dataReader = new DataFieldsReader(data);

            string toUserName   = dataReader.GetFieldData(Field.MessageUserDest);
            string fromUserName = dataReader.GetFieldData(Field.MessageUserOrigin);
            string message      = dataReader.GetFieldData(Field.MessageText);

            SendIM(toUserName, fromUserName, message);
        }

        public void SendIM(string toUserName, string fromUserName, string message)
        {
            dataWriter = new DataFieldsWriter();

            dataWriter.WriteField(Field.MessageUserOrigin, fromUserName);
            dataWriter.WriteField(Field.MessageUserDest,   toUserName);
            dataWriter.WriteField(Field.MessageText,       message);
            dataWriter.WriteField(Field.MessageUserFullName, Database.GetFullName(fromUserName));

            netServer.SendNetMsg(toUserName, NetServices.SendMessage, dataWriter.GetString());
        }

        public void Notify(string toUserName, NetMsg msg)
        {
            netServer.SendNetMsg(toUserName, msg);
        }
        #endregion
    }
}
